package com.zzxx.photograph.web.servlet;

import com.zzxx.photograph.domain.ResultInfo;
import com.zzxx.photograph.domain.User;
import com.zzxx.photograph.exception.LoginException;
import com.zzxx.photograph.service.UserService;
import com.zzxx.photograph.service.impl.UserServiceImpl;
import com.zzxx.photograph.util.Md5Util;
import com.zzxx.photograph.web.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    // /user/checkUsername
    public void checkUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean isExists = userService.usernameIsExists(username);
        ResultInfo info = new ResultInfo(!isExists);
        writeValue(resp, info);
    }

    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        ResultInfo info = new ResultInfo();
        try {
            // 注册一个转换器  String -> Date
            ConvertUtils.register(new Converter() {
                @Override
                public Object convert(Class type, Object value) {
                    // 将String类型的value 转换成Date类型的值返回
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        return sf.parse(value.toString());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            }, Date.class);

            BeanUtils.populate(user, req.getParameterMap());
            user.setPassword(Md5Util.encodeByMd5(user.getPassword()));
            // 注册, 没有出现异常, 有可能成功, 也有可能失败
            boolean flag = userService.register(user);
            info.setFlag(flag);
        } catch (Exception e) {
            // 出现异常, 注册失败了
            e.printStackTrace();
            info.setFlag(false);
        }
        if (!info.isFlag()) { // 如果失败, 传递错误信息
            info.setErrorMsg("注册失败");
        }
        writeValue(resp, info);
    }

    public void active(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        boolean flag = userService.activeUser(code);
        if (flag) {
            resp.sendRedirect(req.getContextPath() + "/active_ok.html");
        } else {
            resp.sendRedirect(req.getContextPath() + "/error/active_error.html");
        }
    }

    // /user/login
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String check = req.getParameter("check");
        // 1.判断验证码是否正确
        ResultInfo info = null;
        if (check != null && check.equalsIgnoreCase(req.getSession().getAttribute("CHECKCODE_SERVER").toString())) {
            try {
                // 密码加密
                password = Md5Util.encodeByMd5(password);
                User user = userService.login(username, password);
                // 登录成功, 将user存储到session中
                req.getSession().setAttribute("user", user);
                info = new ResultInfo(true);
            } catch (LoginException e) {
                // 登录失败
                info = new ResultInfo(false, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            info = new ResultInfo(false, "验证码错误");
        }
        writeValue(resp, info);
    }

    //     /user/findOne 查询用户的登录信息
    public void findOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object user = req.getSession().getAttribute("user");
        ResultInfo info = new ResultInfo();
        if (user == null) {
            info.setFlag(false);
        } else {
            info.setFlag(true);
            info.setData(user);
        }
        writeValue(resp, info);
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("user");
        ResultInfo info = new ResultInfo(true);
        writeValue(resp, info);
    }

    //修改密码
    public void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> map = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, req.getParameterMap());
            userService.updatePasswordByUsername(user.getUsername(), Md5Util.encodeByMd5(user.getPassword()));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResultInfo info = new ResultInfo(true);
        writeValue(resp, info);
    }

    public void getUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _uid = req.getParameter("uid");
        int uid = Integer.parseInt(_uid);
        User user = userService.getUserByUid(uid);
        ResultInfo info = new ResultInfo();
        info.setData(user);
        writeValue(resp, info);
    }

    public void updateInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        User user = new User();
//        Map<String, String[]> map = req.getParameterMap();
//        System.out.println(map);
        try {
//            ConvertUtils.register(new Converter() {
//                @Override
//                public Object convert(Class type, Object value) {
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                    try {
//                        return sdf.parse(value.toString());
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    }
//                    return null;
//                }
//            }, Date.class);
            BeanUtils.populate(user, req.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        String uid = req.getParameter("uid");
        userService.updateInfoByUid(uid, user);
//        System.out.println(uid);
//        System.out.println(user);
        req.getSession().removeAttribute("user");
        ResultInfo info = new ResultInfo(true);
        writeValue(resp, info);
    }

    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String uid = req.getParameter("uid");
        userService.deleteUserByUid(uid);
        req.getSession().removeAttribute("user");
        ResultInfo info = new ResultInfo(true);
        writeValue(resp, info);
    }

    public void sendMsg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String message = req.getParameter("message");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        userService.sendMsg(name, email, message);
        writeValue(resp, true);
    }

    public void sendEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        boolean flag = userService.sendEmail(email);
        if (flag) {
            resp.sendRedirect(req.getContextPath() + "/active_ok.html");
        }
        writeValue(resp, true);
    }
}
